package com.common.frame.lifecycle

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.common.frame.base.debugLog
import com.common.frame.base.getSimpleName
import java.lang.ref.WeakReference
import java.util.*

class ActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {

    var store: Stack<WeakReference<Activity>> = Stack()
    var mCurrentActivity: Activity? = null
    var lastFinishActivity: String? = null//最后一次关闭的页面名称

    private var mForegroundCount = 0
    private var mConfigCount = 0
    private var mIsBackground = false

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        if (store.isEmpty()) {
            "activityManager : AppState = ${ActivityStateType.START.desc}".debugLog()
            ActivityStateLiveData.setActivityState(ActivityStateType.START)
//            isForeground()
        }
        val weakActivity = WeakReference(activity);
        store.add(weakActivity)
        mCurrentActivity = activity
        "activityManager : Created = ${activity.getSimpleName()}".debugLog()
    }

    override fun onActivityStarted(activity: Activity) {
        val simpleName = activity.getSimpleName()
        "activityManager : onStart = $simpleName".debugLog()
        ActivityStateLiveData.setActivityState(ActivityStateType.ACTIVITY_ON_START)
        "activityManager : $simpleName AppState = ${ActivityStateType.ACTIVITY_ON_START.desc}".debugLog()

        if (mConfigCount < 0) {
            ++mConfigCount
        } else {
            ++mForegroundCount
        }
    }

    override fun onActivityResumed(activity: Activity) {
        mCurrentActivity = activity
        val simpleName = activity.getSimpleName()
        "activityManager : onResume = $simpleName".debugLog()
        ActivityStateLiveData.setActivityState(ActivityStateType.ACTIVITY_ON_RESUME)
        "activityManager : $simpleName AppState = ${ActivityStateType.ACTIVITY_ON_RESUME.desc}".debugLog()

        if (mIsBackground) {
            mIsBackground = false
            isForeground()
        }
    }

    override fun onActivityPaused(activity: Activity) {
        val simpleName = activity.getSimpleName()
        lastFinishActivity = simpleName
        "activityManager : Paused = $simpleName".debugLog()
    }

    override fun onActivityStopped(activity: Activity) {
        val simpleName = activity.getSimpleName()
        lastFinishActivity = simpleName
        "activityManager : Stopped = $simpleName".debugLog()
        ActivityStateLiveData.setActivityState(ActivityStateType.ACTIVITY_ON_STOP)
        "activityManager : $simpleName AppState = ${ActivityStateType.ACTIVITY_ON_STOP.desc}".debugLog()

        if (activity.isChangingConfigurations) {
            --mConfigCount
        } else {
            --mForegroundCount
            if (mForegroundCount <= 0) {
                mIsBackground = true
                isForeground()
            }
        }
    }

    override fun onActivityDestroyed(activity: Activity) {
        lastFinishActivity = activity.getSimpleName()
        if (store.size == 1) {
            val lastActivity = store[0].get()
            if (lastActivity != null && activity.localClassName == lastActivity.localClassName) {
                ActivityStateLiveData.setActivityState(ActivityStateType.END)
                "activityManager : AppState = ${ActivityStateType.END.desc}".debugLog()
            }
        }

        val temp: MutableList<WeakReference<Activity>> = ArrayList()
        for (weakReference in store) {
            if (weakReference.get() != null && activity.localClassName == weakReference.get()!!.localClassName) {
                temp.add(weakReference)
            }
        }

        if (temp.size > 0) {
            store.removeAll(temp.toSet())
        }
        "activityManager : Destroyed = ${activity.getSimpleName()}".debugLog()
    }

    /**
     * 是否在前台
     */
    fun isAppInForeground(): Boolean = !mIsBackground

    /**
     * 是否在前台/后台
     */
    private fun isForeground(){
        val state = if (mIsBackground) ActivityStateType.BACKGROUND else ActivityStateType.FOREGROUND
        ActivityStateLiveData.setActivityState(state)
        "activityManager : AppState = ${state.desc}".debugLog()
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        "activityManager : SaveInstanceState = ${activity.getSimpleName()}".debugLog()
    }

    /**
     * 获取当前的Activity
     *
     * @return
     */
    fun getCurrentActivity(): Activity? {
        if (mCurrentActivity != null) {
            "activityManager : getCurrentActivity = ${mCurrentActivity!!.getSimpleName()}".debugLog()
            return mCurrentActivity
        }
        if (store.size > 0) {
            val activity = store.lastElement().get()
            activity?.let {
                "activityManager : getCurrentActivity = ${it.getSimpleName()}".debugLog()
            }
            return activity
        }
        return null
    }

    /**
     * 获取倒数第二个activity
     */
    fun getLastTwo(): Activity? {
        if (store.size >= 2) {
            return store[store.size - 2].get()
        }
        return null
    }

    fun getActivity(cls: Class<*>): Activity? {
        store.forEach {
            if (it.get()?.javaClass == cls) {
                return it.get()
            }
        }
        return null
    }

    fun getActivity(simpleName: String): Activity? {
        store.forEach {
            if (it.get()?.javaClass?.simpleName == simpleName) {
                return it.get()
            }
        }
        return null
    }

    /**
     * 保留最后一个，关闭其他页面
     */
    fun finishOtherActivity() {
        val lastActivity = store.lastElement().get()
        for (activity in store) {
            if (activity.get() != null && lastActivity !== activity.get()) {
                activity.get()!!.finish()
            }
        }
    }

    /**
     * 保留指定页面，关闭其他页面
     *
     * @param saveActivity
     */
    fun finishOtherActivity(saveActivity: Activity) {
        for (activity in store) {
            if (activity.get() != null && saveActivity !== activity.get()) {
                activity.get()!!.finish()
            }
        }
    }

    /**
     * 保留指定页面，关闭其他页面
     *
     * @param activityName
     */
    fun finishOtherActivity(activityName: String) {
        if (activityName.isEmpty()) {
            return
        }
        for (activity in store) {
            if (activity.get() != null) {
                if (activityName == activity.get()!!.javaClass.simpleName) {
                    continue
                }
                activity.get()!!.finish()
            }
        }
    }

    /**
     * 关闭所有页面
     */
    fun finishAllActivity() {
        for (activity in store) {
            if (activity.get() != null) {
                activity.get()!!.finish()
            }
        }
    }

    fun finishActivity(activityName: String) {
        if (activityName.isEmpty()) {
            return
        }
        for (activity in store) {
            if (activity.get() != null && activityName == activity.get()!!.javaClass.simpleName) {
                activity.get()!!.finish()
                break
            }
        }
    }

    fun lastFinishActivityName(): String? {
        return lastFinishActivity
    }

    /**
     * 页面是否打开过
     */
    fun isInActivityStack(activityName: String): Boolean {
        if (activityName.isEmpty()) {
            return false
        }
        for (activity in store) {
            if (activity.get() != null) {
                if (activityName == activity.get()!!.javaClass.simpleName) {
                    return true
                }
            }
        }
        return false
    }

    fun hasActivity(cls: Class<*>): Boolean {
        store.forEach {
            if (it.get()?.javaClass == cls) {
                return true
            }
        }
        return false
    }

}